//
//  LoadingProgressView.m
//  BSProject
//
//  Created by nsm on 2019/10/19.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "LoadingProgressView.h"

@interface LoadingProgressView ()
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@end

@implementation LoadingProgressView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize {
    _progress = 0;
    _progressColor = UIColor.whiteColor;

    _progressLayer = [CAShapeLayer layer];
    _progressLayer.fillColor = UIColor.clearColor.CGColor;
    _progressLayer.strokeColor = _progressColor.CGColor;
    _progressLayer.strokeStart = 0;
    _progressLayer.strokeEnd = 0;
    [self.layer addSublayer:_progressLayer];
}

- (void)setProgressColor:(UIColor *)progressColor {
    _progressColor = progressColor;
    _progressLayer.strokeColor = progressColor.CGColor;
}

- (void)setProgress:(CGFloat)progress {
    _progress = MIN(MAX(0, progress), 1);
    
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    _progressLayer.strokeEnd = _progress;
    [CATransaction commit];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (!CGRectEqualToRect(_progressLayer.frame, self.bounds)) {
        _progressLayer.frame = self.bounds;
    }
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, self.height/2)];
    [path addLineToPoint:CGPointMake(self.width, self.height/2)];
    path.lineCapStyle = kCGLineCapRound;
    
    _progressLayer.path = path.CGPath;
    _progressLayer.lineWidth = self.height;
}

@end
